package com.joysuch.wwyt.bp.websocket;

import com.joysuch.wwyt.api.dataaccess.DataAccessService;
import com.joysuch.wwyt.api.dataaccess.bean.OrgCodeBean;
import com.joysuch.wwyt.bp.entity.BpEnterpriseInfo;
import com.joysuch.wwyt.bp.entity.BpWorkSafetyCertType;
import com.joysuch.wwyt.bp.repository.BpEnterpriseInfoDao;
import com.joysuch.wwyt.bp.repository.BpWorkSafetyCertTypeDao;
import com.joysuch.wwyt.bp.service.BpWorkSafetyCertService;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Log
@Transactional
public class WorkSafetyApplicationRunner implements ApplicationRunner {

    @Autowired
    private BpWorkSafetyCertService bpWorkSafetyCertService;
    @Autowired
    private DataAccessService dataAccessService;
    @Autowired
    private BpEnterpriseInfoDao bpEnterpriseInfoDao;
    @Autowired
    private BpWorkSafetyCertTypeDao bpWorkSafetyCertTypeDao;

    @Override
    public void run(ApplicationArguments args) {
        if (!dataAccessService.isWorkLevelOpen()) {
            return;
        }
        List<BpWorkSafetyCertType> list = bpWorkSafetyCertService.getWorkCertType();
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        //查询所有企业,设置虚拟用户
        List<BpEnterpriseInfo> all = bpEnterpriseInfoDao.findAll();
        if (!CollectionUtils.isEmpty(all)) {
            for (BpEnterpriseInfo e : all) {
                //构造调用数据
                Map<OrgCodeBean, List<String>> map = new HashMap<>();
                List<String> sList = new ArrayList<>();
                OrgCodeBean orgCodeBean = new OrgCodeBean();
                orgCodeBean.setOrgCode(e.getOrgCode());
                orgCodeBean.setTenentId(e.getTenentId());
                for (BpWorkSafetyCertType type : list) {
                    if (type.getOrgCode().equals(e.getOrgCode()) && type.getTenentId().equals(e.getTenentId())) {
                        sList.add(type.getName() + "作业");
                        //修改状态->已同步
                        type.setSyncState(1);
                        bpWorkSafetyCertTypeDao.save(type);
                    }
                }
                map.put(orgCodeBean, sList);
                if (!CollectionUtils.isEmpty(sList)) {
                    dataAccessService.workLevel(map);
                }
            }
        }
    }
}
